<template>
  <nut-popup 
    :visible="visible" 
    position="bottom" 
    class="disease-selectors"
    :style="{ height: '85%' }"    
    @close="handleClose"
  >
    <view class="disease-selector-popup">
      <!-- 弹窗头部 -->
      <view class="popup-header">
        <text class="popup-title">选择疾病</text>
        <view class="close-btn" @click="handleClose">
          <text>✕</text>
        </view>
      </view>
      
      <!-- 弹窗内容 -->
      <view class="popup-contents">
        <!-- 筛选框 -->
        <view class="filter-section">
          <view class="filter-input-wrapper">
            <view class="search-icon">
              <text class="icon-text">🔍</text>
            </view>
            <input 
              class="filter-input"
              placeholder="搜索疾病名称..."
              :value="filterText"
              @input="handleFilterInput"
            />
            <view v-if="filterText" class="clear-btn" @click="clearFilter">
              <text class="clear-text">✕</text>
            </view>
          </view>
        </view>

        <!-- 疾病列表 -->
        <view class="selection-content">
          <view v-if="loading" class="loading-container">
            <text class="loading-text">正在加载疾病列表...</text>
          </view>
          <view v-else-if="filteredDiseaseList.length === 0" class="empty-container">
            <text class="empty-text">{{ filterText ? '未找到匹配的疾病' : '暂无疾病数据' }}</text>
          </view>
          <view v-else class="disease-list">
            <view 
              v-for="disease in filteredDiseaseList" 
              :key="disease.id"
              class="disease-item"
              :class="{ 'selected': selectedDisease?.id === disease.id }"
              @click="selectDisease(disease)"
            >
              <view class="disease-info">
                <text class="disease-name">{{ disease.name }}</text>
                <text v-if="disease.description" class="disease-desc">{{ disease.description }}</text>
              </view>
              <view v-if="selectedDisease?.id === disease.id" class="selected-icon">
                <text class="check-icon">✓</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      
      <!-- 底部按钮 -->
      <view class="popup-footer">
        <view class="button-group">
          <nut-button 
            type="default" 
            class="cancel-btn"
            @click="handleClose"
          >
            取消
          </nut-button>
          <nut-button 
            type="primary" 
            class="confirm-btn"
            :disabled="!selectedDisease"
            @click="handleConfirm"
          >
            确定
          </nut-button>
        </view>
      </view>
    </view>
  </nut-popup>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { request } from '@/service/request'

interface Disease {
  id: string | number
  name: string
  code?: string
  description?: string
}

interface Props {
  /** 弹窗显示状态 */
  visible: boolean
  /** 项目组ID */
  projectId?: string
}

interface Emits {
  /** 更新visible状态事件，用于支持v-model */
  (e: 'update:visible', value: boolean): void
  /** 关闭弹窗事件 */
  (e: 'close'): void
  /** 确认选择事件 */
  (e: 'confirm', disease: Disease): void
}

const props = withDefaults(defineProps<Props>(), {
  projectId: '1976949825857019906'
})

const emit = defineEmits<Emits>()

// 疾病选择相关状态
const diseaseList = ref<Disease[]>([])
const selectedDisease = ref<Disease | null>(null)
const loading = ref(false)
const filterText = ref('')


// 计算属性：筛选后的疾病列表
const filteredDiseaseList = computed(() => {
  if (!filterText.value.trim()) return diseaseList.value
  
  const keyword = filterText.value.toLowerCase().trim()
  return diseaseList.value.filter(disease => 
    disease.name?.toLowerCase().includes(keyword) ||
    disease.description?.toLowerCase().includes(keyword)
  )
})


/**
 * 获取疾病列表
 */
const fetchDiseaseList = async () => {
  try {
    loading.value = true
    
    const response = await request.get<any>('/health_disease/healthDisease/list', {
      projectid: props.projectId
    }, {
      useErrMsg: true
    })
    console.log("获取疾病列表响应:", response)
    if (response.success && Array.isArray(response.success.records)) {
      diseaseList.value = response.success.records
    } else {
      console.warn('疾病列表数据格式异常:', response.success)
      diseaseList.value = []
    }
  } catch (error) {
    console.error('获取疾病列表失败:', error)
    diseaseList.value = []
  } finally {
    loading.value = false
  }
}

/**
 * 选择疾病
 */
const selectDisease = (disease: Disease) => {
  selectedDisease.value = disease
}

/**
 * 处理确认选择
 */
const handleConfirm = () => {
  if (selectedDisease.value) {
    emit('confirm', selectedDisease.value)
  }
  handleClose()
}

/**
 * 处理关闭弹窗
 */
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

/**
 * 处理筛选输入
 */
const handleFilterInput = (event: any) => {
  filterText.value = event.detail.value
}

/**
 * 清空筛选
 */
const clearFilter = () => {
  filterText.value = ''
}

/**
 * 重置选择状态
 */
const resetSelection = () => {
  selectedDisease.value = null
  filterText.value = ''
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 弹窗打开时，加载疾病数据
    fetchDiseaseList()
  } else {
    // 弹窗关闭时，重置状态
    resetSelection()
  }
})

// 暴露方法给父组件
defineExpose({
  resetSelection
})
</script>

<style scoped lang="scss">
.disease-selectors{
  :deep(.nut-popup){
    border-radius: 50rpx 50rpx 0 0;
    overflow: hidden;
  }

}
// 疾病选择弹窗样式
.disease-selector-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
  border-radius: 24rpx 24rpx 0 0; // 顶部圆角
  
  .popup-header {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 32rpx;
    border-bottom: 1rpx solid #f0f0f0;
    position: relative;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-btn {
      position: absolute;
      right: 32rpx;
      top: 50%;
      transform: translateY(-50%);
      width: 56rpx;
      height: 56rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 40rpx;
      color: #999;
      cursor: pointer;
      
      &:active {
        opacity: 0.6;
      }
    }
  }
  
  .popup-contents {
    flex: 1;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    
    .filter-section {
      padding: 24rpx;
      border-bottom: 1rpx solid #f0f0f0;
      background: #fafafa;
      
      .filter-input-wrapper {
        position: relative;
        display: flex;
        align-items: center;
        background: white;
        border-radius: 12rpx;
        border: 2rpx solid #e9ecef;
        padding: 0 24rpx;
        height: 80rpx;
        transition: all 0.3s ease;
        
        &:focus-within {
          border-color: #3b82f6;
          box-shadow: 0 0 0 4rpx rgba(59, 130, 246, 0.1);
        }
        
        .search-icon {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16rpx;
          flex-shrink: 0;
          width: 32rpx;
          height: 32rpx;
          
          .icon-text {
            font-size: 24rpx;
            color: #999;
          }
        }
        
        .filter-input {
          flex: 1;
          height: 100%;
          border: none;
          outline: none;
          font-size: 28rpx;
          color: #333;
          background: transparent;
          height: 60rpx;
          line-height: 60rpx;
          display: flex;
          align-items: center;
          
          &::placeholder {
            color: #999;
            font-size: 28rpx;
          }
        }
        
        .clear-btn {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-left: 16rpx;
          padding: 8rpx;
          cursor: pointer;
          border-radius: 50%;
          width: 32rpx;
          height: 32rpx;
          transition: all 0.2s ease;
          
          .clear-text {
            font-size: 20rpx;
            color: #999;
            line-height: 1;
          }
          
          &:active {
            background: #f0f0f0;
          }
        }
      }
    }
    
    .selection-content {
      padding: 24rpx;
      flex: 1;
      overflow-y: auto;
      
      .loading-container, .empty-container {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 200rpx;
        
        .loading-text, .empty-text {
          font-size: 28rpx;
          color: #666;
        }
      }
    }
  }
  
  .popup-footer {
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    border-top: 1rpx solid #f0f0f0;
    
    .button-group {
      display: flex;
      gap: 16rpx;
      
      .cancel-btn, .confirm-btn {
        flex: 1;
        height: 80rpx;
        border-radius: 12rpx;
        font-size: 28rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      .cancel-btn {
        background: #f8f9fa;
        color: #6c757d;
        border: 1rpx solid #dee2e6;
      }
      
      .confirm-btn {
        background: #3b82f6;
        color: white;
        border: none;
        
        &:disabled {
          background: #e9ecef;
          color: #6c757d;
        }
      }
    }
  }
}

// 疾病列表样式
.disease-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}


.disease-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
  
  &.selected {
    background: #e3f2fd;
    border-color: #3b82f6;
  }
  
  &:active {
    opacity: 0.8;
  }
  
  .disease-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8rpx;
    
    .disease-name {
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
    }
    
    .disease-desc {
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .selected-icon {
    margin-left: 16rpx;
    
    .check-icon {
      font-size: 20rpx;
      color: #3b82f6;
      font-weight: bold;
    }
  }
}
</style>
